package org.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.reggie.common.R;
import org.example.reggie.dto.DishDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.example.reggie.entity.*;
import org.example.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 菜品
 */
@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {

    @Resource
    private DishService dishService;
    @Resource
    private DishFlavorService dishFlavorService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private SetmealService setmealService;
    @Resource
    private SetmealDishService setmealDishService;


    /**
     * 菜品管理展示
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        Page<Dish> p=new Page<>(page, pageSize);
        Page<DishDto>p1=new Page<>();
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
         if (name != null) {
              wrapper.like(Dish::getName,name);
         }
         wrapper.orderByDesc(Dish::getPrice);
         dishService.page(p,wrapper);
         //对象拷贝
        BeanUtils.copyProperties(p,p1,"records");
        List<Dish> records = p.getRecords();
        List<DishDto> list= records.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            //分类id
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String name1 = category.getName();
                dishDto.setCategoryName(name1);
            }
          return dishDto;
        }).collect(Collectors.toList());
        p1.setRecords(list);
        return R.success(p1);
    }
    /**
     * 添加菜品
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithDishFlavor(dishDto);
        return R.success("新增菜品成功！");
    }

    /**
     * 添加菜品
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        Dish dish = new Dish();
        dishService.updateById(dishDto);
        LambdaQueryWrapper<DishFlavor> lambda = new LambdaQueryWrapper<>();
        lambda.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(lambda);
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
        return R.success("修改成功！");
    }

    /**
     * 批量删除
     */
    @DeleteMapping
    public R<String> delete(long[] ids) {
        for (long id : ids) {
            dishService.removeById(id);
        }

         return R.success("批量删除成功！");
    }

    /**
     *
     * 批量停售和批量起售
     */
    @PostMapping("/status/{status}")
    public R<String> status(long [] ids,@PathVariable int status){
         for (long id : ids) {
             LambdaQueryWrapper<Dish> eq =new LambdaQueryWrapper<>();
              eq.eq(Dish::getId,id);
              Dish dish = dishService.getOne(eq);
              dish.setStatus(status);
             dishService.updateById(dish);

                 LambdaQueryWrapper<SetmealDish>wrapper=new LambdaQueryWrapper<>();
                 wrapper.eq(SetmealDish::getDishId,dish.getId());
                 List<SetmealDish> setmealDishes = setmealDishService.list(wrapper);
                 setmealDishes.forEach(dish11 -> {
                     Setmeal setmeal = setmealService.getById(dish11.getSetmealId());
                     if (setmeal != null) {
                         setmeal.setStatus(status);
                         setmealService.updateById(setmeal);
                     }
                 });
         }

        return R.success("批量修改成功！");
    }

    //点餐标签展示
    @PostMapping("/orderstatus/{orderStatus}")
    public R<String> orderStatus(long id,@PathVariable int orderStatus){
        dishService.updateOrderStatus(orderStatus,id);
        String orderstatus=orderStatus==0?"1":"0";
        return R.success(orderstatus);
    }

    //点餐初始化
    @PostMapping("/initializeOrderStatus")
    public R<String> initializeOrderStatus(){
        dishService.initializeOrderStatus();
        return R.success("ok");
    }
    //购物车
    @PostMapping("/shoppingcar")
    public R<List<Dish>> shoppingCar( long[] ids){
     //   QueryWrapper<Dish> wrapper=new QueryWrapper<Dish>().in("id",ids);

      List<Dish> dish = dishService.listByIds(Arrays.asList( ArrayUtils.toObject(ids)));
        return R.success(dish);
    }
    /**
     * id查询菜品返回前端
     */
    @GetMapping("/{id}")
    public R<DishDto> id(@PathVariable long id) {
        DishDto dishDto= dishService.getDishDto(id);
         return R.success(dishDto);
    }
    /**
     * 根据分类id查询所以的菜品
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        List<Dish> list = dishService.list(new QueryWrapper<Dish>().eq("category_id",
        dish.getCategoryId()).eq("status",1));
        List<DishDto>dtoList=null;
        dtoList=list.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
           Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //菜品id
            Long dishId = item.getId();
            List<DishFlavor> flavorList =
                    dishFlavorService.list(new LambdaQueryWrapper<DishFlavor>().eq(DishFlavor::getDishId, dishId));
            dishDto.setFlavors(flavorList);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dtoList);
    }


}
